/*Copyright (C) 2024  深圳极向量科技有限公司 All Rights Reserved.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.*/

package neatlogic.module.change.api;

import com.alibaba.fastjson.JSONObject;
import neatlogic.framework.auth.core.AuthAction;
import neatlogic.framework.change.constvalue.*;
import neatlogic.framework.change.dto.ChangeStepVo;
import neatlogic.framework.change.dto.ChangeVo;
import neatlogic.framework.change.dto.ProcessTaskStepChangeVo;
import neatlogic.framework.change.exception.ChangeHandleHasNotStartedException;
import neatlogic.framework.change.exception.ChangeNoPermissionException;
import neatlogic.framework.change.exception.ChangeNotFoundException;
import neatlogic.framework.common.constvalue.ApiParamType;
import neatlogic.framework.common.constvalue.GroupSearch;
import neatlogic.framework.crossover.CrossoverServiceFactory;
import neatlogic.framework.process.auth.PROCESS_BASE;
import neatlogic.framework.process.crossover.IProcessStepHandlerCrossoverUtil;
import neatlogic.framework.process.crossover.IProcessTaskCrossoverMapper;
import neatlogic.framework.process.dto.ProcessTaskStepRemindVo;
import neatlogic.framework.process.dto.ProcessTaskStepVo;
import neatlogic.framework.process.exception.process.ProcessStepUtilHandlerNotFoundException;
import neatlogic.framework.process.stephandler.core.IProcessStepInternalHandler;
import neatlogic.framework.process.stephandler.core.ProcessStepInternalHandlerFactory;
import neatlogic.framework.restful.annotation.Description;
import neatlogic.framework.restful.annotation.Input;
import neatlogic.framework.restful.annotation.OperationType;
import neatlogic.framework.restful.annotation.Param;
import neatlogic.framework.restful.constvalue.OperationTypeEnum;
import neatlogic.framework.restful.core.privateapi.PrivateApiComponentBase;
import neatlogic.module.change.dao.mapper.ChangeMapper;
import neatlogic.module.change.service.ChangeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
@AuthAction(action = PROCESS_BASE.class)
@OperationType(type = OperationTypeEnum.OPERATE)
public class ChangeRestartApi extends PrivateApiComponentBase {

    @Autowired
    private ChangeMapper changeMapper;

    @Autowired
    private ChangeService changeService;

    @Override
    public String getToken() {
        return "change/restart";
    }

    @Override
    public String getName() {
        return "nmca.changerestartapi.getname";
    }

    @Override
    public String getConfig() {
        return null;
    }

    @Input({
            @Param(name = "changeId", type = ApiParamType.LONG, isRequired = true, desc = "term.change.changeid"),
            @Param(name = "content", type = ApiParamType.STRING, desc = "common.content"),
            @Param(name = "source", type = ApiParamType.STRING, desc = "common.source")
    })
    @Description(desc = "nmca.changerestartapi.getname")
    @Override
    public Object myDoService(JSONObject jsonObj) throws Exception {
        Long changeId = jsonObj.getLong("changeId");
        ChangeVo changeVo = changeMapper.getChangeById(changeId);
        if (changeVo == null) {
            throw new ChangeNotFoundException(changeId);
        }
        /* 获取当前变更锁 **/
        changeMapper.getChangeLockById(changeId);

        String owner = changeMapper.getChangeUserByChangeId(changeId);
        if (StringUtils.isNotBlank(owner)) {
            changeVo.setOwner(GroupSearch.USER.getValuePlugin() + owner);
        }
        changeVo.setChangeStepList(changeMapper.getChangeStepListByChangeId(changeId));
        if (!changeService.isRestartableChange(changeVo)) {
            throw new ChangeNoPermissionException(ChangeOperationType.RESTARTCHANGE.getText());
        }
        /** 重新开始变更时，将变更状态设置为“待处理”，变更步骤状态设置为“待处理”,is_active为0 **/
        changeVo.setStatus(ChangeStatus.PENDING.getValue());
        changeMapper.updateChangeStatus(changeVo);

        ChangeStepVo changeStepVo = new ChangeStepVo();
        changeStepVo.setAutoGenerateId(false);
        changeStepVo.setChangeId(changeId);
        changeStepVo.setStatus(ChangeStatus.PENDING.getValue());
        changeStepVo.setIsActive(0);
        changeMapper.updateChangeStepStatus(changeStepVo);
        changeMapper.updateChangeStepIsActive(changeStepVo);
        /** 将变更状态设置为“处理中” **/
        changeVo.setStatus(ChangeStatus.RUNNING.getValue());
        changeMapper.updateChangeStatus(changeVo);

        /** 重新开始变更时，触发激活变更步骤 **/
        changeService.activeChangeStep(changeId);

        /** 重新开始变更时，触发更新processtask_step_worker和processtask_step_user数据 **/
        ProcessTaskStepChangeVo processTaskStepChangeVo = changeMapper.getProcessTaskStepChangeHandleByChangeId(changeId);
        if (processTaskStepChangeVo == null) {
            throw new ChangeHandleHasNotStartedException();
        }
        IProcessStepInternalHandler processStepUtilHandler = ProcessStepInternalHandlerFactory.getHandler(ChangeProcessStepHandlerType.CHANGEHANDLE.getHandler());
        if (processStepUtilHandler == null) {
            throw new ProcessStepUtilHandlerNotFoundException(ChangeProcessStepHandlerType.CHANGEHANDLE.getHandler());
        }
        processStepUtilHandler.updateProcessTaskStepUserAndWorker(processTaskStepChangeVo.getProcessTaskId(), processTaskStepChangeVo.getProcessTaskStepId());
        IProcessTaskCrossoverMapper processTaskCrossoverMapper = CrossoverServiceFactory.getApi(IProcessTaskCrossoverMapper.class);
        /** 生成活动 **/
        ProcessTaskStepVo currentProcessTaskStepVo = processTaskCrossoverMapper.getProcessTaskStepBaseInfoById(processTaskStepChangeVo.getProcessTaskStepId());
        currentProcessTaskStepVo.getParamObj().putAll(jsonObj);
        IProcessStepHandlerCrossoverUtil processStepHandlerCrossoverUtil = CrossoverServiceFactory.getApi(IProcessStepHandlerCrossoverUtil.class);
        processStepHandlerCrossoverUtil.audit(currentProcessTaskStepVo, ChangeAuditType.RESTARTCHANGE);
        processStepHandlerCrossoverUtil.notify(currentProcessTaskStepVo, ChangeTriggerType.RESTARTCHANGE);
        processStepHandlerCrossoverUtil.action(currentProcessTaskStepVo, ChangeTriggerType.RESTARTCHANGE);
        processTaskCrossoverMapper.deleteProcessTaskStepRemind(new ProcessTaskStepRemindVo(processTaskStepChangeVo.getProcessTaskStepId(), ChangeRemindType.PAUSECHANGE.getValue()));
        return null;
    }

}
